<?php

namespace App\Http\Controllers\Api;

use App\GameChannel\PayGameCallback;
use App\Http\Controllers\Controller;
use App\Jobs\PaySuccessQueue;
use App\Models\Orders;
use App\Models\OrdersCallClient;
use App\Models\UserAccount;
use App\Services\SdkService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Crypt;

class SysController extends Controller
{
    public function __construct(Request $request)
    {
        // 校验签名
        $ret = SdkService::getInstance()->checkSign($request->input());
        if ($ret === false) {
            return yqerr(101);
        }
    }

    // 补单功能
    public function budan(Request $request)
    {
        $trade_no = $request->input('trade_no');
        $order = Orders::where('trade_no', $trade_no)->first();

        if ($order->status == Orders::PAY_STATUS_CALLBACK_OK) {
            return yqerr(6049);
        }

        // 如果此订单未支付成功的，那么补单后进行一次 支付成功后处理其他附加任务
        $status_create = false;
        if (in_array($order->status, [Orders::PAY_STATUS_CREATE])) {
            $status_create = true;
        }

        $obj = new PayGameCallback($trade_no);
        $ret = $obj->cbGameByBudan();
        if (!$ret) {
            return yqerr(6028);
        }

        $call = OrdersCallClient::where('order_id', $order->id)->first();
        if ($status_create == true && !$call) {
            PaySuccessQueue::dispatch($trade_no)->onQueue('default');
        }

        return yqok();
    }

    // 修改用户密码
    public function userAccountPasswordUpdate(Request $request)
    {
        $id = $request->input('id');
        $password = $request->input('password');

        $class           = UserAccount::find($id);
        $class->password = Crypt::encryptString($password);
        $ret             = $class->save();

        if ($ret === true) {
            return yqok();
        } else {
            return yqerr(6042);
        }
    }
}
